<?php
/**
 * 用户操作
 */

namespace App\Services;

use App\Models\MemberRelation;
use DB;
use App\Models\Member;

class MemberService extends BaseService
{
    /**
     * 根据uuid获取姓名
     * @param $uuid
     * @return string
     */
    public static function getNameByUuid($uuid)
    {
        try {
            if (!$uuid) {
                throw new \Exception('uuid不能为空');
            }

            $oMember = Member::select(['name'])->where('uuid', $uuid)->first();
            if (is_null($oMember)) {
                throw new \Exception('没有数据');
            }

            return $oMember->name;

        } catch (\Exception $e) {
            return '未知姓名';
        }
    }

    /**
     * 根据uuid获取电话
     *
     * @param $uuid
     * @return mixed|string
     */
    public static function getPhoneByUuid($uuid)
    {
        try {
            if (!$uuid) {
                throw new \Exception('uuid不能为空');
            }

            $oMember = Member::query()->select('phone')->where('uuid', $uuid)->first();
            if (is_null($oMember)) {
                throw new \Exception('没有数据');
            }

            return $oMember->phone;

        } catch (\Exception $e) {
            return '';
        }
    }

    /**
     * 新增普通用户
     * @param $parentId
     * @param $mobile 手机号
     * @param string $name 姓名
     * @param $userType 角色
     * @return object
     * @throws \Exception
     */
    public function addGeneralMember($parentId, $mobile, $name = '', $userType)
    {
        // 添加员工
        $user = Member::create([
            'phone'   => $mobile,
            'name'    => $name,
            'uuid'    => \Faker\Provider\Uuid::uuid(),
            'role_id' => 0, //普通员工
        ]);

        // 新增关联关系
        MemberRelation::create([
            'parent_id' => $parentId,
            'member_id' => $user->id,
            'role_id'   => $userType,
        ]);

        return $user;
    }

}